package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.comment.vos.ApCommentVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    GreenTextScan greenTextScan;

    @Autowired
    UserFeign userFeign;

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    CommentHotService commentHotService;

    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        try {
            // 1. 校验参数
            ApUser user = AppThreadLocalUtils.getUser();
            // 校验是否登录
            if (user==null) {
                CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
            }
            // 校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验)
            // 2. 阿里云校验评论内容是否违规
            //(简单:  此步不做      普通: 阿里云检测有问题提示      高级:  有问题不报异常，替换为**)
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            String filteredContent = (String) map.get("filteredContent");
            String content1 = (String) map.get("content");
            System.out.println(filteredContent);
            System.out.println(content1);
            if (!suggestion.equals("pass")) {
                dto.setContent(filteredContent);
            }
            // 3. 远程查询当前登陆用户信息
            ResponseResult<ApUser> userResult = userFeign.findUserById(user.getId());
            if (!userResult.checkCode() || userResult.getData()==null) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用apUserFeign失败");
            }
            ApUser apUser = userResult.getData();
            // 4. 创建评论信息，并保存到mongo
            ResponseResult<ApArticle> articleResult = articleFeign.findByArticleId(dto.getArticleId());
            if (!articleResult.checkCode()) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用articleFeign失败");
            }
            ApArticle article = articleResult.getData();
            ApComment apComment = new ApComment();
            apComment.setArticleId(dto.getArticleId());
            apComment.setAuthorId(apUser.getId());
            apComment.setAuthorName(apUser.getName());
            apComment.setContent(dto.getContent());
            apComment.setImage(apUser.getImage());
            apComment.setChannelId(article.getChannelId());
            apComment.setCreatedTime(new Date());
            apComment.setUpdatedTime(new Date());
            apComment.setFlag((short) 0);
            apComment.setType((short) 0);
            //...
            apComment.setLikes(0);
            apComment.setReply(0);
            mongoTemplate.save(apComment);
            return ResponseResult.okResult();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Autowired
    RedissonClient redissonClient;

    @Override
    public ResponseResult like(CommentLikeDTO dto) {
       //1. 参数校验
       //评论id不能为空  operation必须为 0  或  1
       //2. 根据评论id查询评论数据， 为null返回错误信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        RLock rlock = redissonClient.getLock("like-lock");
        ApComment apComment;
        try {
            rlock.lock();
            //3. 如果是点赞操作 判断是否已经点赞
            apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
            if (apComment==null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //点过赞提示 请勿重复点赞
            ApCommentLike apCommentLike = mongoTemplate.findOne(
                    Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId())),
                    ApCommentLike.class);
            if (apCommentLike!=null && dto.getOperation().intValue()==0) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"已点赞");
            }
            //未点过赞   保存点赞信息到mongo
            if (dto.getOperation().intValue()==0) {
                //并修改评论信息的点赞数量( + 1)
                apComment.setLikes(apComment.getLikes()+1);
                mongoTemplate.save(apComment);
                ApCommentLike commentLike = new ApCommentLike();
                commentLike.setCommentId(apComment.getId());
                commentLike.setOperation((short) 0);
                commentLike.setAuthorId(user.getId());
                mongoTemplate.save(commentLike);
                //计算热点评论评论
                if (apComment.getLikes() >= 10 && apComment.getFlag().shortValue() == 0) {
                    commentHotService.hotCommentExecutor(apComment);
                }
            }else {
                //4. 如果是取消点赞操作
                //        删除点赞信息
                mongoTemplate.remove( Query.query( Criteria.
                        where("authorId").is(user.getId())
                        .and("commentId").is(apComment.getId()) ), ApCommentLike.class);
                //修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes()-1);
                mongoTemplate.save(apComment);
            }
        } finally {
            rlock.unlock();
        }
        //5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        Map<String,Object> map = new HashMap<>();
        map.put("likes",apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
      // 1. 参数校验 校验文章id
        if (dto==null || dto.getArticleId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
      // 校验size
        Integer size = dto.getSize();
        if (size ==null || size <=0) {
            size=10;
        }
      // 2. 根据条件查询评论列表
        List<ApComment> apCommentList=null;
        //首页
        if (dto.getIndex().intValue()==1) {
            //热点// (文章id  , flag:1, likes降序)
            apCommentList = mongoTemplate.find(Query.query(Criteria.where("articleId")
                    .is(dto.getArticleId()).and("flag").is(1))
                    .with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);
            if (CollectionUtils.isNotEmpty(apCommentList)) {
                // (文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
                size = size - apCommentList.size();
                List<ApComment> simpleCommentList = mongoTemplate.find(query(dto, size), ApComment.class);
                apCommentList.addAll(simpleCommentList);
            }else {
                apCommentList = mongoTemplate.find(query(dto,size),ApComment.class);
            }
        }
      // 3. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            // 4. 如果未登录直接返回评论列表
            return ResponseResult.okResult(apCommentList);
        }
      // 5. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        List<String> commentIds = apCommentList.stream().map(ApComment::getId).collect(Collectors.toList());
        // 5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
        // commentId  in    评论id列表   authorId = 登录人id
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(Query.query(Criteria.where("commentId").in(commentIds)
                .and("authorId").is(user.getId())), ApCommentLike.class);
        if (CollectionUtils.isNotEmpty(apCommentList) && CollectionUtils.isNotEmpty(apCommentLikes)) {
            //5.2 遍历评论列表
            //将每一个评论  ApComment 转成 ApCommentVO
            //其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
            List<String> likeIds = apCommentLikes.stream().map(ApCommentLike::getCommentId).collect(Collectors.toList());

            return ResponseResult.okResult(apCommentList.stream().map(comment -> parseCommentVO(comment,likeIds)));

        }
        return ResponseResult.okResult(apCommentList);
    }

    private Object parseCommentVO(ApComment comment, List<String> likeIds) {
        ApCommentVo apCommentVo = new ApCommentVo();
        BeanUtils.copyProperties(comment, apCommentVo);
        if (likeIds.contains(apCommentVo.getId())){
            apCommentVo.setOperation((short) 0);
        }
        return apCommentVo;
    }

    //查询条件(文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
    private Query query(CommentDTO dto, Integer size) {
        return Query.query(Criteria.where("articleId").is(dto.getArticleId())
                .and("flag").is(0).and("createdTime").lt(dto.getMinDate()))
                .limit(size).with(Sort.by(Sort.Direction.DESC, "createdTime"));
    }
}
